

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;

import kr.molit.common.Helper;
import kr.molit.service.impl.InterlockServiceImpl;
import kr.molit.vo.AttachVO;
import kr.molit.vo.DeptVO;
import kr.molit.vo.MinwonVO;
import kr.molit.vo.OfficeVO;
import kr.molit.vo.TransferVO;

/**
 * Description : 
 * @author
 * @since
 * @version
 * @see
 *
 * <pre>
 * << Modification Information >>
 *   
 *   Date     Modifier               Expression
 *  -------    --------    ---------------------------
 *  
 *
 * 
 * </pre>
 */
public class InterlockTask
{
	Logger logger = Logger.getLogger(InterlockTask.class);
	
	@Resource(name = "interlockService")
    private InterlockService interlockService;

	@Resource(name = "minwonService")
    private MinwonService minwonService;

	@Scheduled(fixedDelay=5000)
	public void doService()
	{
		List<TransferVO> list = interlockService.getTransferTask();
		for (TransferVO tran : list)
		{
			logger.info(String.format("mwId:%d : %s - %s, %s", tran.mwId, tran.name, tran.method, tran.url));
			
			tran.result = "T";
			tran.msg    = "�꾩넚 �쒖옉";
			interlockService.updateTransfer(tran);
			
			try
			{
				Class<?> cls = this.getClass();
				Method method = cls.getMethod(tran.method, TransferVO.class);
				if (method == null)
					throw new Exception("Interlock : no such method - " + tran.method);
				JSONObject obj = (JSONObject)method.invoke(this, tran);
				if (obj.getBoolean("success")==false)
				{
					tran.msg = obj.getString("msg");
					throw new Exception("��긽�쒕쾭�먯꽌 �ㅻ쪟瑜�諛섑솚�덉뒿�덈떎");
				}
				
				tran.result = "S";
				tran.msg    = "�깃났";
			}
			catch (Exception ex)
			{
				logger.error(ex);
				tran.result = "F";
			}
			
			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			tran.transDate = f.format(new Date());
			
			interlockService.updateTransfer(tran);
		}
	}
	
	private static class CustomHostnameVerifier implements HostnameVerifier
	{
		@Override
		public boolean verify(String paramString, SSLSession paramSSLSession) {
			return true;
		}
	}
	
	public JSONObject httpsBasic(TransferVO tran) throws Exception
	{
		try
		{
			logger.info("httpsBasic");
			
			JSONObject obj = createMinwonData(tran);
			
			URL url = new URL(tran.url);
			HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
			con.setHostnameVerifier(new CustomHostnameVerifier());
	
			return doPost(con, obj);
		}
		catch (Exception ex)
		{
			logger.error(ex);
			tran.msg    = ex.getMessage();
			throw ex;
		}
	}
	
	public JSONObject httpBasic(TransferVO tran) throws Exception
	{
		try
		{
			logger.info("httpsBasic");
			
			JSONObject obj = createMinwonData(tran);
			
			URL url = new URL(tran.url);
			HttpURLConnection con = (HttpURLConnection)url.openConnection();
	
			return doPost(con, obj);
		}
		catch (Exception ex)
		{
			logger.error(ex);
			tran.msg    = ex.getMessage();
			throw ex;
		}
	}
	
	private JSONObject doPost(HttpURLConnection con, JSONObject obj) throws Exception
	{
		con.setDoOutput(true);
		con.setConnectTimeout(10 * 1000);
		con.setReadTimeout(10 * 1000);
		
		OutputStream os = null;
		InputStream  is = null;

		try
		{
			os = con.getOutputStream();
			
			os.write(obj.toString().getBytes("UTF-8"));
			os.flush();

			is = con.getInputStream();
			return this.readResponse(is);
		}
		catch (Exception ex)
		{
			Helper.closeStream(os);
			Helper.closeStream(is);
			throw ex;
		}
	}
	
	private JSONObject readResponse(InputStream input) throws IOException 
	{
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		IOUtils.copy(input, output);
		
		String res = output.toString("UTF-8");
		logger.info(res);
		
		return JSONObject.fromObject(res);
	}

	JSONObject createMinwonData(TransferVO tran)
	{
		MinwonVO   minwon = this.minwonService.getMinwonInfo(tran.mwId.toString());
		JSONObject obj = new JSONObject();
		
		obj.put("mwId", minwon.mwId);
		obj.put("mwNm", minwon.mwNm);
		obj.put("mwTel", minwon.mwTel);
		obj.put("code", minwon.code);
		obj.put("mwType", minwon.mwType);
		obj.put("mwName", minwon.mwName);
		obj.put("mwLatitude", minwon.latitude);
		obj.put("mwLongitude", minwon.longitude);
		obj.put("direction", minwon.direction);
		obj.put("mwAddr", minwon.addr);
		obj.put("mwRoad", minwon.ROAD_NAME);
		obj.put("mwContent", minwon.mwContent);
		obj.put("regDate", Helper.safeSubstr(Helper.safestr(minwon.regDate), 0, 19));

		JSONArray files = new JSONArray();
		List<AttachVO> fileList = minwon.getFileList();
		for (AttachVO attach : fileList)
		{
			JSONObject file = new JSONObject();
			
			file.put("fileType", attach.fileType);
			file.put("contentTpe", attach.contentType);
			file.put("url", "https://127.0.0.1:8443/molit/readFile.do?name=" + attach.fileId);
			files.add(file);
		}
		obj.put("files", files);
		
		return obj;
	}
}
